﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Net.Mail;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI;

namespace Core
{
    /// <summary>
    /// các thuộc tính đăng nhập
    /// </summary>
    public class Utils
    {
        public static readonly SHA1CryptoServiceProvider PWD_CRYPTO = new SHA1CryptoServiceProvider();
        public static string sConnectString = ConfigurationSettings.AppSettings["ConnectString"];
        /// <summary>
        /// Lấy tên đăng nhập của người dùng
        /// </summary>
        /// <returns></returns>
        public string GetUserName()
        {
            string sRes = "";
            if (HttpContext.Current.Session[Constants.session_user_name] != null)
            {
                sRes = HttpContext.Current.Session[Constants.session_user_name].ToString();
            }
            return sRes;
        }
        public static string setHoverMenu(string htmlCode, string requestMenu, string insertString)
        {
            if (htmlCode.Contains(requestMenu))
            {
                htmlCode = htmlCode.Replace(insertString, "");
                int index = htmlCode.IndexOf(" href='" + requestMenu);
                return htmlCode.Insert(index, insertString);
            }
            return htmlCode;
        }
       
        /// <summary>
        /// Lấy ID đơn vị của người dùng
        /// </summary>
        /// <returns></returns>
        public long GetIdDepartment()
        {
            long iRes = 0;
            if (HttpContext.Current.Session[Constants.session_user_department] != null)
            {
                iRes = long.Parse(HttpContext.Current.Session[Constants.session_user_department].ToString());
            }
            return iRes;
        }

        /// <summary>
        /// Lấy Họ tên của người dùng
        /// </summary>
        /// <returns></returns>
        public string GetFullName()
        {
            string sRes = "";
            if (HttpContext.Current.Session[Constants.session_full_name] != null)
            {
                sRes = HttpContext.Current.Session[Constants.session_full_name].ToString();
            }
            return sRes;
        }

        /// <summary>
        /// Lấy đơn vị thao tác dựa trên miền dữ liệu đc phân
        /// </summary>
        public long LayDonviThaoTac(long _idVaiTro, long _idNguoiDung, string _sMaTaiNguyen, string _sMaThaoTac, string _sTenControl)
        {
            long lngRes = 0;
            DataSet dts = null;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[5];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@in_vaiTroId";
                commandParameter[0].Value = _idVaiTro;

                commandParameter[1] = new SqlParameter();
                commandParameter[1].ParameterName = "@in_nguoiDungId";
                commandParameter[1].Value = _idNguoiDung;

                commandParameter[2] = new SqlParameter();
                commandParameter[2].ParameterName = "@in_maTaiNguyen";
                commandParameter[2].Value = _sMaTaiNguyen;

                commandParameter[3] = new SqlParameter();
                commandParameter[3].ParameterName = "@in_maThaoTac";
                commandParameter[3].Value = _sMaThaoTac;

                commandParameter[4] = new SqlParameter();
                commandParameter[4].ParameterName = "@in_tenControl";
                commandParameter[4].Value = _sTenControl;

                if (commandParameter != null)
                {
                    dts = SqlHelper.ExecuteDataset(sConnectString, "sp_LayMienDuLieu", commandParameter);
                    if (dts != null)
                    {
                        if (dts.Tables.Count > 0)
                        {
                            if (dts.Tables[0].Rows.Count > 0)
                            {
                                lngRes = long.Parse(dts.Tables[0].Rows[0]["fk_iDonViID"].ToString());
                                dts = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
                lngRes = 0;
            }
            return lngRes;
        }

        /// <summary>
        /// Check Quyền thao tác
        /// </summary>
        /// <param name="_iNguoiDungID"></param>
        /// <param name="_iDonViID"></param>
        /// <param name="_iVaiTroID"></param>
        /// <param name="_sTenControl"></param>
        /// <param name="_sMaTaiNguyen"></param>
        /// <param name="_sMaThaoTac"></param>
        /// <returns></returns>
        public bool checkQuyenThaoTac(long _iNguoiDungID, long _iDonViID, long _iVaiTroID, string _sTenControl, string _sMaTaiNguyen, string _sMaThaoTac)
        {
            bool bRes = false;
            DataSet dts = null;
            try
            {
                SqlParameter[] commandParameter = null;
                commandParameter = new SqlParameter[6];

                commandParameter[0] = new SqlParameter();
                commandParameter[0].ParameterName = "@in_nguoiDungId";
                commandParameter[0].Value = _iNguoiDungID;

                commandParameter[1] = new SqlParameter();
                commandParameter[1].ParameterName = "@in_donViId";
                commandParameter[1].Value = _iDonViID;

                commandParameter[2] = new SqlParameter();
                commandParameter[2].ParameterName = "@in_vaiTroId";
                commandParameter[2].Value = _iVaiTroID;

                commandParameter[3] = new SqlParameter();
                commandParameter[3].ParameterName = "@in_tenControl";
                commandParameter[3].Value = _sTenControl;

                commandParameter[4] = new SqlParameter();
                commandParameter[4].ParameterName = "@in_maTaiNguyen";
                commandParameter[4].Value = _sMaTaiNguyen;

                commandParameter[5] = new SqlParameter();
                commandParameter[5].ParameterName = "@in_maThaoTac";
                commandParameter[5].Value = _sMaThaoTac;

                if (commandParameter != null)
                {
                    dts = SqlHelper.ExecuteDataset(sConnectString, "sp_CheckQuyenThaoTac", commandParameter);
                    if (dts != null)
                    {
                        if (dts.Tables.Count > 0)
                        {
                            if (dts.Tables[0].Rows.Count > 0)
                            {
                                bRes = bool.Parse(dts.Tables[0].Rows[0]["ketQua"].ToString());
                                dts = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
              
                bRes = false;
            }
            return bRes;
        }


       
        /// <summary>
        /// SendMail
        /// </summary>
        /// <param name="_fromEmail"></param>
        /// <param name="toAddress"></param>
        /// <param name="cc"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="_displayName"></param>
        /// <param name="bytearray"></param>
        /// <param name="strAttach"></param>
        /// <param name="strsmtpServer"></param>
        /// <param name="intsmtpPort"></param>
        /// <param name="struserName"></param>
        /// <param name="strpass"></param>
        /// <param name="bolenableSsl"></param>
        /// <returns></returns>
        public static bool SendMail(string _fromEmail, string toAddress, string cc, string subject,
                string body, string _displayName, Byte[] bytearray, string strAttach, string strsmtpServer,
                int intsmtpPort, string struserName, string strpass, bool bolenableSsl)
        {
            bool checkOk = true;
            MailMessage message = new MailMessage();
            message.IsBodyHtml = true;
            string fromAddress = _fromEmail;
            string displayName = _displayName;
            message.From = new MailAddress(fromAddress, displayName);
            message.Subject = subject;
            message.SubjectEncoding = Encoding.UTF8;
            string Attach = strAttach;
            MemoryStream StreamToAttach = new MemoryStream(bytearray);
            Attachment _att = new Attachment(StreamToAttach, Attach);
            message.Attachments.Add(_att);
            string[] s = toAddress.Split(';');
            message.To.Add(new MailAddress(s[0]));
            if (cc.Trim() != "")
            {
                foreach (string st in cc.Split(';'))
                    message.CC.Add(new MailAddress(st));
            }
            message.Body = body;
            message.BodyEncoding = Encoding.UTF8;

            string smtpServer = strsmtpServer;
            int smtpPort = intsmtpPort;
            string strEmailAddress = struserName;
            string strEmailPassword = strpass;
            bool enableSsl = bolenableSsl;
            SmtpClient smtp = new SmtpClient();
            smtp.Credentials = new System.Net.NetworkCredential(strEmailAddress, strEmailPassword);
            smtp.Port = smtpPort;
            smtp.Host = smtpServer;
            smtp.EnableSsl = enableSsl;
            try
            {
                smtp.Send(message);
            }
            catch (Exception ex)
            {
                checkOk = false;
                
            }
            return checkOk;
        }

        public static bool SendMail(string _fromEmail, string toAddress, string subject, string body, string _displayName,
                string strsmtpServer, int intsmtpPort, string struserName, string strpass, bool bolenableSsl)
        {
            bool checkOk = true;
            MailMessage message = new MailMessage();
            message.IsBodyHtml = true;
            string fromAddress = _fromEmail;
            string displayName = _displayName;
            message.From = new MailAddress(fromAddress, displayName);
            message.Subject = subject;
            message.SubjectEncoding = Encoding.UTF8;
            string[] s = toAddress.Split(';');
            message.To.Add(new MailAddress(s[0]));
            message.Body = body;
            message.BodyEncoding = Encoding.UTF8;

            string smtpServer = strsmtpServer;
            int smtpPort = intsmtpPort;
            string strEmailAddress = struserName;
            string strEmailPassword = strpass;
            bool enableSsl = bolenableSsl;
            SmtpClient smtp = new SmtpClient();
            smtp.Credentials = new System.Net.NetworkCredential(strEmailAddress, strEmailPassword);
            smtp.Port = smtpPort;
            smtp.Host = smtpServer;
            smtp.EnableSsl = enableSsl;
            try
            {
                smtp.Send(message);
            }
            catch (Exception ex)
            {
                checkOk = false;
               
            }
            return checkOk;
        }

        /// <summary>
        /// Sinh chuoi ngau nhien
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RandomString(int length)
        {
            try
            {
                Random r = new Random(Environment.TickCount);
                string chars = "0123456789abcdefghijklmnopqrstuvwxyz";
                StringBuilder builder = new StringBuilder(length);

                for (int i = 0; i < length; ++i)
                {
                    builder.Append(chars[r.Next(chars.Length)]);
                }
                return builder.ToString();
            }
            catch (Exception ex)
            {
                
                return "";
            }
        }

        /// <summary>
        /// Sinh mat khau ngau nhien (chuoi ki tu co do dai la 6)
        /// </summary>
        /// <returns></returns>
        public static string RandomPassword()
        {
            return RandomString(6);
        }

        /// <summary>
        /// Lấy sesstion, check timeout
        /// </summary>
        /// <param name="response"></param>
        /// <param name="page"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetSession_value(HttpResponse response, Page page, string request)
        {
            if (HttpContext.Current.Session[request] != null)
            {
                return HttpContext.Current.Session[request].ToString();
            }
            response.Redirect(page.ResolveUrl("~/") + "Admin/Login.aspx");
            return "";
        }

        /// <summary>
        /// Lấy ID người dùng đăng nhập
        /// </summary>
        /// <returns></returns>
        public static long GetUserId()
        {
            long lngRes = 0;
            if (HttpContext.Current.Session[Constants.session_user_id] != null)
            {
                lngRes = long.Parse(HttpContext.Current.Session[Constants.session_user_id].ToString());
            }
            return lngRes;
        }

        /// <summary>
        /// Lấy ID của đơn vị gốc theo ID đơn vị truyền vào
        /// </summary>
        /// <param name="_DepartmentID"></param>
        /// <returns></returns>
        public static long GetRootDepartmentID(long _DepartmentID)
        {
            long lngRes = 0;
            using (SqlConnection conn = new SqlConnection(sConnectString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT dbo.f_LayDonViRootID(" + _DepartmentID + ")", conn))
                {
                    conn.Open();
                    lngRes = (long)cmd.ExecuteScalar();
                    conn.Close();
                }
            }
            return lngRes;
        }

        #region Các hàm chuyển đổi, convert, Mã hóa

        /// <summary>
        /// Xóa khoảng trắng thừa
        /// </summary>
        /// <param name="_string"></param>
        /// <returns></returns>
        public string ChuanHoaXau(string _string)
        {
            StringBuilder kq = new StringBuilder();
            _string = _string.Trim();
            for (int i = 0; i < _string.Length; i++)
            {
                kq.Append(_string[i]);
                if (_string[i] == ' ')
                {
                    while (_string[i] == ' ')
                    {
                        i++;
                    }
                    kq.Append(_string[i]);
                }
            }
            return kq.ToString();
        }

        /// <summary>
        /// Mã hóa
        /// </summary>
        /// <param name="toEncrypt"></param>
        /// <param name="key">key mã hóa(24 kí tự)</param>
        /// <param name="useHashing">Sử dụng MD5</param>
        /// <returns></returns>
        public string EncryptCode(string toEncrypt, string key, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// Giải mã
        /// </summary>
        /// <param name="toDecrypt"></param>
        /// <param name="key"></param>
        /// <param name="useHashing"></param>
        /// <returns></returns>
        public static string DecryptCode(string toDecrypt, string key, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }

        /// <summary>
        /// hàm chuyển tiếng việt sang không dấu
        /// </summary>
        /// <param name="_string"></param>
        /// <returns></returns>
        public string ConvertToUnSign(string _string)
        {
            if (_string == string.Empty || _string == null)
            {
                return "";
            }
            for (int i = 33; i < 48; i++)
            {
                _string = _string.Replace(((char)i).ToString(), "");
            }

            for (int i = 58; i < 65; i++)
            {
                _string = _string.Replace(((char)i).ToString(), "");
            }

            for (int i = 91; i < 97; i++)
            {
                _string = _string.Replace(((char)i).ToString(), "");
            }

            for (int i = 123; i < 127; i++)
            {
                _string = _string.Replace(((char)i).ToString(), "");
            }

            //text = text.Replace(" ", "-"); //Comment lại để không đưa khoảng trắng thành ký tự -

            Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");

            string strFormD = _string.Normalize(System.Text.NormalizationForm.FormD);

            return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }

        /// <summary>
        /// Mã hóa pass 1 chiều
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string EncryptUsingMD5(string password)
        {
            try {
                if (password == null) throw new ArgumentNullException("password");

                byte[] encryptedBytes = PWD_CRYPTO.ComputeHash(Encoding.UTF8.GetBytes(password));

                StringBuilder sb = new StringBuilder();
                foreach (byte b in encryptedBytes) sb.AppendFormat("{0:x2}", b);

                return sb.ToString();
            }
            catch (Exception ex)
            {
                
            }
            return "";
        }
        #endregion

        /// <summary>
        /// Mã hóa 1 chiều
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string HashPassword(string password)
        {
            try
            {
                if (password == null) throw new ArgumentNullException("password");

                byte[] encryptedBytes = PWD_CRYPTO.ComputeHash(Encoding.UTF8.GetBytes(password));

                StringBuilder sb = new StringBuilder();
                foreach (byte b in encryptedBytes) sb.AppendFormat("{0:x2}", b);

                return sb.ToString();
            }
            catch (Exception ex)
            {
              
                return "";
            }
        }
    }
}
